/*
daytime tcp client.
**/

#include <error.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>


int
main(int argc, char **argv) {
	if (argc < 2)
		error_quit("usage: %s ip [port]", argv[0]);

	const char *ip = argv[1];
	int port = argc >= 3 ? atoi(argv[2]) : 13;

	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd < 0)
		error_dump("fail to create socket fd");

	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);
    if (inet_pton(server_addr.sin_family, ip, &server_addr.sin_addr) != 1)
        error_quit("fail to pton");

    if (connect(fd, (struct sockaddr*)&server_addr, sizeof(server_addr)))
        error_dump("fail to connect");

    const int max_line = 4096;
    char buffer[max_line];
    ssize_t n;
    while ((n=read(fd, buffer, max_line)) > 0) {
        buffer[n] = 0;
        error_msg("server day time:%s", buffer);
    }

    if (n < 0)
        error_dump("fail to read data");

    error_msg("server close connection");
    close(fd);
    return 0;
}
